package org.qydjk.h5.controller.common;

import com.google.code.kaptcha.Producer;
import org.qydjk.common.constant.CommonConstant;
import org.qydjk.common.util.IOUtil;
import org.qydjk.h5.controller.base.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Controller
@RequestMapping("/common")
public class CommonController extends BaseController{
    @Autowired
    private Producer captchaProducer;

    @RequestMapping("/captcha.do")
    public void captcha() throws IOException {
        response.setHeader("Pragma","no-cache");
        response.setHeader("Cache-Control","no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        String text = captchaProducer.createText();
        session.setAttribute(CommonConstant.KAPTCHA_SESSION_KEY, text);
        ServletOutputStream out = null;
        try {
            BufferedImage img = captchaProducer.createImage(text);
            out = response.getOutputStream();
            // write the data out
            ImageIO.write(img, "jpg", out);
            out.flush();
        } finally {
            out.close();
        }
    }
}
